from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule
import scrapy, time
from w3lib.html import remove_tags
from kyqb_collection_spider.spiders.common import CommonCrawlSpider
from kyqb_collection_spider.items import KyqbCollectionSpiderItem


class HarvardSpider(CommonCrawlSpider):
    name = 'harvard'
    start_urls = ['https://news.harvard.edu/gazette/section/science-technology/']
    custom_settings = {
        'ITEM_PIPELINES': {'kyqb_collection_spider.pipelines.NewImagesPipeline': 5,
                           'kyqb_collection_spider.pipelines.KyqbCollectionSpiderPipeline': 600},
    }

    rules = (
        Rule(LinkExtractor(restrict_xpaths=('//*[@class="nav-previous"]')), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        article_list = response.xpath('//*[@id="main"]/div/div/div[2]/div')
        for article in article_list:
            href = article.xpath('.//a/@href').extract_first()
            if not self.redis.sismember(self.name, href):
                yield scrapy.Request(url=href, callback=self.article)
            else:
                return None

    def article(self, response):
        try:
            item = KyqbCollectionSpiderItem()
            item['data_address'] = response.url
            item['website_name'] = 'HARVARD'
            item['spider_name'] = self.name
            item['data_source_type'] = '科技网站'
            item['data_type'] = 'NEWS'
            item['collection_mode'] = 'spider'
            item['collection_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
            timestamp = response.xpath('//*[@class="timestamp timestamp--published"]/text()|'
                                       '//*[@class="timestamp timestamp--published-and-updated"]/text()').extract_first().strip()
            item['publish_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(timestamp, "%B %d, %Y"))
            title = response.xpath('/html/body/div/main/article/div[1]/div[1]/header/div/h1/text()').extract_first()
            item['title'] = remove_tags(title)
            item['abstract'] = response.xpath('/html/body/div/main/article/div[2]/h2/text()').extract_first()
            item['topic'] = None
            containers = response.xpath('//*[@class="article-body basic-text  do-drop-cap"]//text()|'
                                        '//*[@class="photo-layout__text"]//text()|'
                                        '//*[@class="article-body basic-text "]//text()|'
                                        '//*[@class="article-body basic-text"]//text()').extract()
            texts = []
            for container in containers:
                text = remove_tags(container)
                texts.append(text)
            item['text'] = '\n'.join(texts)
            item['author'] = response.xpath('//*[@class="article-author-name"]/text()').extract_first()
            image_urls = set()
            urls = response.xpath('/html/body/div/main/article//figure//img/@src').extract()
            for url in urls:
                image_urls.add(url)
            item['image_urls'] = list(image_urls)
            yield item
        except Exception as e:
            self.logger.debug(f"采集错误:{response.url}\n{e}")